package com.foreveross.bsl.cmd;

import org.jivesoftware.smack.AccountManager;
import org.jivesoftware.smack.XMPPException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.bsl.Command;
import com.foreveross.bsl.Config;
import com.foreveross.bsl.openfire.OpenfireClient;

public class UserRegisterCmd implements Command {
	
	private static final Logger log = LoggerFactory.getLogger(UserRegisterCmd.class);
	private final Config config;
	private int count=1, from=1;
	
	public UserRegisterCmd(Config config){
		this.config=config;
	}
	
	public UserRegisterCmd(Config config, int from, int count){
		this.config=config;
		this.from=from<=0 ? 1 : from;
		this.count=count<=0 ? 1 : count;
	}

	@Override
	public void execute(){
		final int to=from+count-1;
		OpenfireClient client=new OpenfireClient(this.getHost(), this.getPort());
		AccountManager accountMgr=new AccountManager(client.getConnection());
		try {
			client.connect();
			log.info("begin create {} users...", count);
			int n=0;
			for(int i=from; i<=to; i++){
				String username=OpenfireClient.PREFIX_USERNAME+i;
				try {
					accountMgr.createAccount(username, OpenfireClient.PREFIX_PWD+i);
					n++;
				} catch (XMPPException e) {
					log.error("Error! create account "+username+" error: "+e.getMessage());
				}
				if(i%10==0){
					log.debug("{} users created!", n);
				}
			}
			log.info("Complete the user to create!", n);
		} catch (XMPPException e) {
			log.error("connect "+this.getHost()+":"+this.getPort()+" error!", e);
		}
	}
	
	/**
	 * @return the host
	 */
	public String getHost() {
		return this.config.getProperty("openfire.host", true);
	}

	/**
	 * @return the port
	 */
	public int getPort() {
		return Integer.parseInt(this.config.getProperty("openfire.port", "5222"));
	}

}
